import os
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton, 
                            QLabel, QFileDialog, QComboBox, QGroupBox, 
                            QRadioButton, QButtonGroup, QMessageBox, QProgressBar)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from ffmpeg_liber import FFmpegProcessor

class VideoCropThread(QThread):
    progress_update = pyqtSignal(int)
    process_finished = pyqtSignal(bool, str)
    
    def __init__(self, input_file, output_file, crop_params, use_hardware_accel, ffmpeg_path=""):
        super().__init__()
        self.input_file = input_file
        self.output_file = output_file
        self.crop_params = crop_params
        self.use_hardware_accel = use_hardware_accel
        self.ffmpeg = FFmpegProcessor(ffmpeg_path)
        
    def run(self):
        try:
            success = self.ffmpeg.crop_video(
                self.input_file, 
                self.output_file, 
                self.crop_params,
                self.use_hardware_accel,
                progress_callback=self.progress_update.emit
            )
            self.process_finished.emit(success, "" if success else "视频裁切失败")
        except Exception as e:
            self.process_finished.emit(False, f"处理过程中出错: {str(e)}")

class VideoCropPage(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        # 使用父窗口的ffmpeg路径初始化
        ffmpeg_path = parent.ffmpeg_path if hasattr(parent, 'ffmpeg_path') else ""
        self.ffmpeg = FFmpegProcessor(ffmpeg_path)
        # 连接日志信号
        self.ffmpeg.log_message.connect(self.log_message)
        self.input_file = ""
        self.video_width = 0
        self.video_height = 0
        self.video_ratio = 0
        self.initUI()
    
    # 添加日志处理方法
    def log_message(self, message):
        if hasattr(self.parent, 'append_log'):
            self.parent.append_log(message)
    
    def initUI(self):
        main_layout = QVBoxLayout()
        
        # 文件选择区域
        file_group = QGroupBox("选择视频文件")
        file_layout = QHBoxLayout()
        
        self.file_path_label = QLabel("未选择文件")
        self.file_path_label.setWordWrap(True)
        self.browse_button = QPushButton("浏览...")
        self.browse_button.clicked.connect(self.browse_file)
        
        file_layout.addWidget(self.file_path_label, 1)
        file_layout.addWidget(self.browse_button)
        file_group.setLayout(file_layout)
        
        # 视频信息区域
        info_group = QGroupBox("视频信息")
        info_layout = QVBoxLayout()
        
        self.video_info_label = QLabel("请先选择视频文件")
        info_layout.addWidget(self.video_info_label)
        
        info_group.setLayout(info_layout)
        
        # 裁切方式选择
        crop_method_group = QGroupBox("裁切方式")
        crop_method_layout = QVBoxLayout()
        
        self.crop_method_group = QButtonGroup(self)
        
        self.top_bottom_radio = QRadioButton("上下裁切")
        self.left_right_radio = QRadioButton("左右裁切")
        self.left_only_radio = QRadioButton("左裁切")
        self.right_only_radio = QRadioButton("右裁切")
        self.mixed_radio = QRadioButton("混合裁切(上下左右均匀)")
        
        self.top_bottom_radio.setChecked(True)
        
        self.crop_method_group.addButton(self.top_bottom_radio, 1)
        self.crop_method_group.addButton(self.left_right_radio, 2)
        self.crop_method_group.addButton(self.left_only_radio, 3)
        self.crop_method_group.addButton(self.right_only_radio, 4)
        self.crop_method_group.addButton(self.mixed_radio, 5)
        
        crop_method_layout.addWidget(self.top_bottom_radio)
        crop_method_layout.addWidget(self.left_right_radio)
        crop_method_layout.addWidget(self.left_only_radio)
        crop_method_layout.addWidget(self.right_only_radio)
        crop_method_layout.addWidget(self.mixed_radio)
        
        crop_method_group.setLayout(crop_method_layout)
        
        # 目标比例选择
        target_ratio_group = QGroupBox("目标比例")
        target_ratio_layout = QVBoxLayout()
        
        # 添加比例选择组合框
        self.target_ratio_combo = QComboBox()
        # 修改比例选项
        self.target_ratio_combo.addItem("2:1", (2, 1))
        self.target_ratio_combo.addItem("1:2", (1, 2))
        self.target_ratio_combo.addItem("16:9", (16, 9))
        self.target_ratio_combo.addItem("9:16", (9, 16))
        self.target_ratio_combo.addItem("2.35:1", (2.35, 1))
        self.target_ratio_combo.addItem("1:2.35", (1, 2.35))
        self.target_ratio_combo.addItem("一半", "half")  # 添加一半选项
        self.target_ratio_combo.addItem("自定义", "custom")  # 添加自定义选项
        
        self.target_ratio_combo.currentIndexChanged.connect(self.on_ratio_changed)
        target_ratio_layout.addWidget(self.target_ratio_combo)
        
        # 自定义比例输入区域 - 使用QSpinBox替代QComboBox
        self.custom_ratio_widget = QWidget()
        custom_ratio_layout = QHBoxLayout(self.custom_ratio_widget)
        custom_ratio_layout.setContentsMargins(0, 5, 0, 0)
        
        # 导入QSpinBox
        from PyQt5.QtWidgets import QSpinBox, QDoubleSpinBox
        
        # 宽度输入框 - 使用QSpinBox
        self.width_ratio_input = QSpinBox()
        self.width_ratio_input.setRange(1, 100)  # 设置范围从1到100
        self.width_ratio_input.setValue(16)      # 默认值设为16
        self.width_ratio_input.setFixedWidth(80)
        
        # 比例分隔符
        ratio_separator = QLabel(":")
        ratio_separator.setAlignment(Qt.AlignCenter)
        ratio_separator.setFixedWidth(15)
        
        # 高度输入框 - 使用QSpinBox
        self.height_ratio_input = QSpinBox()
        self.height_ratio_input.setRange(1, 100)  # 设置范围从1到100
        self.height_ratio_input.setValue(9)       # 默认值设为9
        self.height_ratio_input.setFixedWidth(80)
        
        # 添加一个占位标签，使输入框居中
        spacer_left = QLabel("")
        spacer_right = QLabel("")
        
        custom_ratio_layout.addWidget(spacer_left, 1)
        custom_ratio_layout.addWidget(self.width_ratio_input, 0)
        custom_ratio_layout.addWidget(ratio_separator, 0)
        custom_ratio_layout.addWidget(self.height_ratio_input, 0)
        custom_ratio_layout.addWidget(spacer_right, 1)
        
        self.custom_ratio_widget.setVisible(False)
        target_ratio_layout.addWidget(self.custom_ratio_widget)
        
        target_ratio_group.setLayout(target_ratio_layout)
        
        # 删除硬件加速选项组
        # hw_accel_group = QGroupBox("硬件加速")
        # hw_accel_layout = QHBoxLayout()
        # 
        # self.hw_accel_label = QLabel("使用硬件加速:")
        # self.hw_accel_status = QLabel("未知")
        # 
        # hw_accel_layout.addWidget(self.hw_accel_label)
        # hw_accel_layout.addWidget(self.hw_accel_status)
        # hw_accel_group.setLayout(hw_accel_layout)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setVisible(False)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        self.start_button = QPushButton("开始裁切")
        self.start_button.clicked.connect(self.start_crop)
        self.start_button.setEnabled(False)
        
        self.cancel_button = QPushButton("取消")
        self.cancel_button.clicked.connect(self.cancel_crop)
        self.cancel_button.setEnabled(False)
        
        button_layout.addWidget(self.start_button)
        button_layout.addWidget(self.cancel_button)
        
        # 添加所有组件到主布局
        main_layout.addWidget(file_group)
        main_layout.addWidget(info_group)
        main_layout.addWidget(crop_method_group)
        main_layout.addWidget(target_ratio_group)
        # 移除硬件加速组件
        # main_layout.addWidget(hw_accel_group)
        main_layout.addWidget(self.progress_bar)
        main_layout.addLayout(button_layout)
        
        self.setLayout(main_layout)
        
        # 删除初始化硬件加速状态的调用
        # self.update_hw_accel_status()
        
    def update_hw_accel_status(self):
        if hasattr(self.parent, 'ffmpeg_accel') and self.parent.ffmpeg_accel:
            self.hw_accel_status.setText("是")
        else:
            self.hw_accel_status.setText("否")
    
    def browse_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择视频文件", "", "视频文件 (*.mp4 *.avi *.mkv *.mov *.wmv);;所有文件 (*)"
        )
        
        if file_path:
            self.input_file = file_path
            self.file_path_label.setText(file_path)
            self.analyze_video()
    
    def analyze_video(self):
        try:
            # 确保ffmpeg路径已设置
            if hasattr(self.parent, 'ffmpeg_path'):
                self.ffmpeg.ffmpeg_path = self.parent.ffmpeg_path
                self.ffmpeg.ffprobe_path = self.parent.ffmpeg_path.replace("ffmpeg.exe", "ffprobe.exe")
                self.log_message(f"使用FFmpeg路径: {self.ffmpeg.ffmpeg_path}")
                self.log_message(f"使用FFprobe路径: {self.ffmpeg.ffprobe_path}")
            
            # 获取视频信息
            self.log_message(f"开始分析视频: {self.input_file}")
            video_info = self.ffmpeg.get_video_info(self.input_file)
            
            if video_info:
                self.video_width = video_info.get('width', 0)
                self.video_height = video_info.get('height', 0)
                
                if self.video_width and self.video_height:
                    self.video_ratio = self.video_width / self.video_height
                    
                    # 更新视频信息显示
                    info_text = f"分辨率: {self.video_width}x{self.video_height}\n"
                    
                    # 确定最接近的标准比例
                    ratio_text = self.get_closest_ratio_text(self.video_ratio)
                    info_text += f"宽高比: {ratio_text} ({self.video_width}:{self.video_height})"
                    
                    self.video_info_label.setText(info_text)
                    self.start_button.setEnabled(True)
                    self.log_message(f"视频分析完成: {info_text}")
                else:
                    self.video_info_label.setText("无法获取视频尺寸信息")
                    self.start_button.setEnabled(False)
                    self.log_message("无法获取视频尺寸信息")
            else:
                self.video_info_label.setText("无法分析视频文件")
                self.start_button.setEnabled(False)
                self.log_message("无法分析视频文件")
                
        except Exception as e:
            error_msg = f"分析视频时出错: {str(e)}"
            self.video_info_label.setText(error_msg)
            self.start_button.setEnabled(False)
            self.log_message(error_msg)
    
    def get_crop_parameters(self):
        # 获取目标比例
        target_ratio_data = self.target_ratio_combo.currentData()
        
        # 处理自定义比例
        if target_ratio_data == "custom":
            try:
                # 从QSpinBox获取值
                width_ratio = float(self.width_ratio_input.value())
                height_ratio = float(self.height_ratio_input.value())
                if width_ratio <= 0 or height_ratio <= 0:
                    return None, "自定义比例必须为正数"
                target_ratio = width_ratio / height_ratio
            except ValueError:
                return None, "自定义比例格式无效，请输入数字"
        # 处理"一半"选项
        elif target_ratio_data == "half":
            # 一半比例，即宽度减半或高度减半
            if self.video_width > self.video_height:  # 横向视频
                target_ratio = (self.video_width/2) / self.video_height
            else:  # 纵向视频
                target_ratio = self.video_width / (self.video_height/2)
        else:
            target_ratio = target_ratio_data[0] / target_ratio_data[1]
        
        # 获取裁切方式
        crop_method = self.crop_method_group.checkedId()
        
        # 计算裁切参数
        if self.video_ratio > target_ratio:  # 视频比目标更宽
            # 需要裁剪宽度
            new_width = int(self.video_height * target_ratio)
            width_diff = self.video_width - new_width
            
            if crop_method == 1:  # 上下裁切 - 不应该裁剪宽度
                return None, "上下裁切方式不适用于当前视频比例，请选择其他裁切方式"
            
            elif crop_method == 2:  # 左右裁切
                left_crop = width_diff // 2
                right_crop = width_diff - left_crop
                return {
                    'x': left_crop,
                    'y': 0,
                    'width': new_width,
                    'height': self.video_height,
                    'pad': False
                }, None
                
            elif crop_method == 3:  # 左裁切
                return {
                    'x': width_diff,
                    'y': 0,
                    'width': new_width,
                    'height': self.video_height
                }, None
                
            elif crop_method == 4:  # 右裁切
                return {
                    'x': 0,
                    'y': 0,
                    'width': new_width,
                    'height': self.video_height
                }, None
                
            elif crop_method == 5:  # 混合裁切
                # 对于宽视频，混合裁切主要还是左右裁切
                left_crop = width_diff // 2
                right_crop = width_diff - left_crop
                return {
                    'x': left_crop,
                    'y': 0,
                    'width': new_width,
                    'height': self.video_height
                }, None
                
        else:  # 视频比目标更高
            # 需要裁剪高度或添加黑边
            new_height = int(self.video_width / target_ratio)
            
            if new_height <= self.video_height:  # 可以通过裁剪实现
                height_diff = self.video_height - new_height
                
                if crop_method == 2:  # 左右裁切 - 不应该裁剪高度
                    return None, "左右裁切方式不适用于当前视频比例，请选择其他裁切方式"
                
                elif crop_method == 1:  # 上下裁切
                    top_crop = height_diff // 2
                    bottom_crop = height_diff - top_crop
                    return {
                        'x': 0,
                        'y': top_crop,
                        'width': self.video_width,
                        'height': new_height,
                        'pad': False
                    }, None
                
            elif crop_method == 3 or crop_method == 4:  # 左裁切或右裁切 - 不适用于高度裁切
                return None, "左裁切或右裁切方式不适用于当前视频比例，请选择其他裁切方式"
                
            elif crop_method == 5:  # 混合裁切
                # 对于高视频，混合裁切主要还是上下裁切
                top_crop = height_diff // 2
                bottom_crop = height_diff - top_crop
                return {
                    'x': 0,
                    'y': top_crop,
                    'width': self.video_width,
                    'height': new_height
                }, None
        
        return None, "无法计算裁切参数"
    
    def start_crop(self):
        if not self.input_file:
            QMessageBox.warning(self, "警告", "请先选择视频文件")
            return
        
        # 计算裁切参数
        crop_params, error_msg = self.get_crop_parameters()
        
        if error_msg:
            QMessageBox.warning(self, "警告", error_msg)
            return
        
        # 选择输出文件
        output_file, _ = QFileDialog.getSaveFileName(
            self, "保存裁切后的视频", "", "视频文件 (*.mp4);;所有文件 (*)"
        )
        
        if not output_file:
            return
        
        # 获取硬件加速设置
        use_hw_accel = hasattr(self.parent, 'ffmpeg_accel') and self.parent.ffmpeg_accel != "cpu"
        
        # 开始裁切
        self.progress_bar.setValue(0)
        self.progress_bar.setVisible(True)
        self.start_button.setEnabled(False)
        self.cancel_button.setEnabled(True)
        
        # 记录日志
        self.log_message(f"开始裁切视频: {self.input_file}")
        self.log_message(f"输出文件: {output_file}")
        self.log_message(f"裁切参数: {crop_params}")
        self.log_message(f"使用硬件加速: {use_hw_accel}")
        
        # 创建并启动裁切线程
        self.crop_thread = VideoCropThread(
            self.input_file, 
            output_file, 
            crop_params, 
            use_hw_accel,
            self.parent.ffmpeg_path if hasattr(self.parent, 'ffmpeg_path') else ""
        )
        self.crop_thread.progress_update.connect(self.update_progress)
        self.crop_thread.process_finished.connect(self.on_crop_finished)
        self.crop_thread.start()
    
    def update_progress(self, progress):
        self.progress_bar.setValue(progress)
    
    def on_crop_finished(self, success, error_msg):
        self.progress_bar.setVisible(False)
        self.start_button.setEnabled(True)
        self.cancel_button.setEnabled(False)
        
        if success:
            QMessageBox.information(self, "完成", "视频裁切完成")
        else:
            QMessageBox.critical(self, "错误", f"视频裁切失败: {error_msg}")
    
    def cancel_crop(self):
        if hasattr(self, 'crop_thread') and self.crop_thread.isRunning():
            # 终止线程
            self.crop_thread.terminate()
            self.crop_thread.wait()
            
            self.progress_bar.setVisible(False)
            self.start_button.setEnabled(True)
            self.cancel_button.setEnabled(False)
            
            QMessageBox.information(self, "已取消", "视频裁切已取消")

    def get_closest_ratio_text(self, ratio):
        """获取最接近的标准比例文本"""
        standard_ratios = [
            (2/1, "2:1"),
            (16/9, "16:9"),
            (2.35, "2.35:1"),
            (1, "1:1"),
            (9/16, "9:16"),
            (1/2, "1:2"),
            (1/2.35, "1:2.35")
        ]
        
        closest = min(standard_ratios, key=lambda x: abs(x[0] - ratio))
        return closest[1]
    
    def on_ratio_changed(self, index):
        """处理比例选择变化"""
        is_custom = self.target_ratio_combo.currentData() == "custom"
        self.custom_ratio_widget.setVisible(is_custom)


def create_crop_page(main_window):
    """创建视频裁切页面"""
    # 创建页面
    page = VideoCropPage(main_window)
    
    # 将页面添加到主窗口的内容栈中
    main_window.content_stack.addTab(page, "视频裁切")
    
    # 添加日志记录功能
    if hasattr(main_window, 'append_log'):
        main_window.append_log("视频裁切页面已加载")
    
    return page





